import uuid

from userApp.userModel.models import UserTable


class UserService:
    def verifyUser(self,user):
        try:
            result = UserTable.objects.get(name=user['name'],password=user['password'])
            result.password=None
        except Exception as err:
            print(err)
            result = None
        return result
    def saveUser(self,user):
        try:
            userModes= UserTable.objects.get(name=user['name'])
            print(userModes)
            # django model 无法找到数据则会抛出异常，说明用户唯一
        except Exception:
            print("register user")
            try:
                userModes= UserTable(id=str(uuid.uuid4()).replace('-', '')[1:5],name=user['name'],password=user['password'],email=user['email'])
                userModes.save()
                user = UserTable.objects.get(name=user['name'],password=user['password'])
                user.password=None
                return user
            except Exception as error:
                print(error)
                return None
        return None
    def getUserInfo(self,user):
        result= UserTable.objects.get(name=user['name'],id=user['id'])
        result.password=None
        return result
    def changeUserInfo(self,name,user):
        if user == None :
            return None
        UserTable.objects.filter(name=name).update(
            name = user['name'],
            email = user['email'],
            phoneNumber = user['phoneNumber']
        )
        return UserTable.objects.get(name=user['name'])
    def upateImg(self,user):
        try:
            print("============")
            print(user['img'])
            model=UserTable.objects.get(name=user['name'])
            model.img = user['img']
            model.save()
            return True
        except Exception as err:
            print(err)
            return False


